# conding = utf-8
import re
import warnings
from utils.functions_utils import random_num,random_str,random_date
import jsonpath
import yaml

from config import extract_url
from utils.functions_utils import random_str, random_num, random_date


def parameterize_convert(parameterize: dict):
    '''
    请求参数转换
    :param parameterize: 需要转换的参数
    :return:
    '''
    for k, v in parameterize.items():
        if isinstance(v, str):
            # 判断是否包含 random_ 关键字，进行随机数替换
            if "random_" in v:
                parameterize[k] = eval(v)
                # if "random_str" in v:
                #     length = int(v.split("(")[1].split(")")[0])  # 获取数字长度
                #     parameterize[k] = random_str(length)
                # elif "random_num" in v:
                #     length = int(v.split("(")[1].split(")")[0])  # 获取数字长度
                #     parameterize[k] = random_num(length)
                # elif "random_date" in v:
                #     fmt = v.split("(")[1].split(")")[0]  # 获取日期格式
                #     parameterize[k] = random_date(fmt)
            elif "$." in v:
                parameterize[k] = parameterize_url_convert(v)
        elif isinstance(v, dict):
            parameterize[k] = parameterize_convert(v)  # 递归处理字典
    print("参数结果：", parameterize)
    return parameterize



def get_extract_by_expression(expression):
    '''
    从参数文件中获取参数数据
    :param expression:
    :return:
    '''
    with open(extract_url, "r", encoding="utf-8") as file:
        content = yaml.safe_load(file)
        return jsonpath.jsonpath(content, expression)[0]


def parameterize_file_convert(parameterizes: list):
    '''
    处理文件上传
    :param parameterizes:
    :return:
    '''
    warnings.simplefilter("ignore", ResourceWarning)
    files = []
    for item in parameterizes:
        file = (
            item["name"],
            (
                item["fileName"],
                open(item["filePath"], "rb"),
                item["fileType"]
            )
        )
        files.append(file)
    return files;


def parameterize_url_convert(url: str):
    expression = re.findall("(\\$(\\.[a-zA-Z0-9]+)+)", url)
    if "$." in url:
        for item in expression:
            # $.medicalRecord.id
            value = get_extract_by_expression(item[0])
            url = url.replace(item[0], str(value))
    return url
